var express = require('express');
var jwt = require('jsonwebtoken');
var CONFIG = require('./../config');
var ocrDao = require('./../dao/ocr');
require('./../util/common');
require('./../util/bootloader');
var router = express.Router();

/**
 * @api {POST} /ocr/v1/getAccessToken 获取access_token
 * @apiDescription 文字识别API需要携带access_token参数，所以首先需要获取access_token参数
 * @apiName getAccessToken
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiParamExample {json} 请求示例:
 * {
 *      "app_sid": "NYL",
 *      "time": "1560505477541",
 *      "sign": "416057ec384b744f4536fddcab24746f"
 * }
 * @apiSampleRequest http://www.niyueling.cn/ocr/getAccessToken
 * @apiSuccessExample {json} 成功响应:
 *     HTTP/1.1 200 OK
*       {
            "status": 200,
            "payload": {
                "status": 200,
                "data": {
                    "refresh_token": "25.4cc74eff1c0e197826d4d147aba670e0.315360000.1876199586.282335-16548033",
                    "expires_in": 2592000,
                    "session_key": "9mzdCPXTtIV1xTIykSsD4mag3SHqp+IKTfAyUBPYceIaaU7G4/acnlj5zPYU3GCVyc/+ngn6F3Vb3gMTKGFhLoJy3KACNQ==",
                    "access_token": "24.319a896835856696896237ef3dba055b.2592000.1563431586.282335-16548033",
                    "scope": "public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_ocr_handwriting brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_household_register brain_ocr_vehicle_certificate wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi",
                    "session_secret": "97c7ff16408c8dd0f2b0f151a9242d2b"
                }
            }
        }
 * @apiSuccess {Number} status 状态码
 * @apiSuccess {Object} payload 返回对象
 * @apiSuccess {String} access_token 获取的access_token
 * @apiSuccess {String} expires_in Access Token的有效期(秒为单位，一般为1个月)
 * 
 * @apiGroup OCR
 * @apiVersion 1.0.0
 */
router.post('/getAccessToken', function (req, res) {
    var par = paramAll(req);

    if (!par.app_sid) {
        return res.json(new ERR('平台标识不为空!', 400));
    }
    if (!par.time) {
        par.time = new Date().getTime();
    }
    if (!par.sign) {
        return res.json(new ERR('sign不为空!', 400));
    }
    if (!checkOvertime(par.time)) {
        return res.json(new ERR('时间戳已过期!', 400));
    }

    //1.加密生成签名sign
    var param = createSign({
        account: par.account,
        app_sid: par.app_sid,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if (param.sign == param.sign) {
        //2.签名验证成功，进入dao层发起http请求获取access_token
        ocrDao.getAccessToken(param, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (data.status == 200) {
                    return res.json(new PKG(data));
                } else {
                    return res.json(new ERR(data, 420));
                }
            }
        });
    } else {
        return res.json(new ERR('sign算法不合法!', 420));
    }
});

/**
 * @api {POST} /ocr/v1/general_basic 通用文字识别
 * @apiDescription 通用文字识别，可以请求识别某张图中的所有文字。
 * @apiName general_basic
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiParamExample {json} 请求示例:
 * {
 *      "app_sid": "NYL",
 *      "time": "1560505477541",
 *      "sign": "416057ec384b744f4536fddcab24746f"
 * }
 * @apiSampleRequest http: //www.niyueling.cn/ocr/v1/general_basic
 * @apiSuccessExample {json} 成功响应:
 *     HTTP/1.1 200 OK
*       {
            "status": 200,
            "payload": {
                "status": 200,
                "data": {
                    "log_id": 1435134591226670800,
                    "words_result_num": 2,
                    "words_result": [
                        {
                            "words": "人就是为了找你,"
                        },
                        {
                            "words": "去你们相遇的地方"
                        }
                    ]
                }
            }
        }
 * @apiSuccess {Number} status 状态码
 * @apiSuccess {Object} payload 返回对象
 * @apiSuccess {String} log_id 唯一的log_id
 * @apiSuccess {String} words_result_num 识别结果数
 * @apiSuccess {String} words_result 识别结果内容
 * 
 * @apiGroup OCR
 * @apiVersion 1.0.0
 */
router.post('/general_basic', function (req, res) {
    var par = paramAll(req);

    if (!par.url) {
        return res.json(new ERR('图片url不为空!', 400));
    }
    if (!par.time) {
        par.time = new Date().getTime();
    }
    if (!par.sign) {
        return res.json(new ERR('sign不为空!', 400));
    }
    if (!checkOvertime(par.time)) {
        return res.json(new ERR('时间戳已过期!', 400));
    }

    //1.加密生成签名sign
    var param = createSign({
        url: par.url,
        app_sid: par.app_sid,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if (param.sign == param.sign) {
        //2.签名验证成功，进入dao层发起http请求获取access_token
        ocrDao.general_basic(param, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (data.status == 200) {
                    return res.json(new PKG(data));
                } else {
                    return res.json(new ERR(data, 420));
                }
            }
        });
    } else {
        return res.json(new ERR('sign算法不合法!', 420));
    }
});

/**
 * @api { POST } /ocr/v1/general 通用文字识别
 * @apiDescription 通用文字识别，可以请求识别某张图中的所有文字。
 * @apiName general
 * @apiParam {String} app_sid 平台标识(必填)
 * @apiParam {String} time 当前时间戳(必填)
 * @apiParam {String} sign 签名(必填)
 * @apiParamExample {json} 请求示例:
 * {
 *      "app_sid": "NYL",
 *      "time": "1560505477541",
 *      "sign": "416057ec384b744f4536fddcab24746f"
 * }
 * @apiSampleRequest http: //www.niyueling.cn/ocr/v1/general
 * @apiSuccessExample {json} 成功响应:
 *     HTTP/1.1 200 OK
*       {
            "status": 200,
            "payload": {
                "status": 200,
                "data": {
                    "log_id": 271531551862122620,
                    "words_result_num": 2,
                    "words_result": [
                        {
                            "location": {
                                "width": 289,
                                "top": 223,
                                "left": 9,
                                "height": 104
                            },
                            "words": "人就是为了找你,"
                        },
                        {
                            "location": {
                                "width": 302,
                                "top": 278,
                                "left": 0,
                                "height": 128
                            },
                            "words": "去你们相遇的地方"
                        }
                    ]
                }
            }
        }
 * @apiSuccess {Number} status 状态码
 * @apiSuccess {Object} payload 返回对象
 * @apiSuccess {String} log_id 唯一的log_id
 * @apiSuccess {String} words_result_num 识别结果数
 * @apiSuccess {String} words_result 识别结果内容
 * 
 * @apiGroup OCR
 * @apiVersion 1.0.0
 */
router.post('/general', function (req, res) {
    var par = paramAll(req);

    if (!par.url) {
        return res.json(new ERR('图片url不为空!', 400));
    }
    if (!par.time) {
        par.time = new Date().getTime();
    }
    if (!par.sign) {
        return res.json(new ERR('sign不为空!', 400));
    }
    if (!checkOvertime(par.time)) {
        return res.json(new ERR('时间戳已过期!', 400));
    }

    //1.加密生成签名sign
    var param = createSign({
        url: par.url,
        app_sid: par.app_sid,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if (param.sign == param.sign) {
        //2.签名验证成功，进入dao层发起http请求获取access_token
        ocrDao.general(param, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (data.status == 200) {
                    return res.json(new PKG(data));
                } else {
                    return res.json(new ERR(data, 420));
                }
            }
        });
    } else {
        return res.json(new ERR('sign算法不合法!', 420));
    }
});

router.post('/handwriting', function (req, res) {
    var par = paramAll(req);

    if (!par.time) {
        par.time = new Date().getTime();
    }
    if (!par.sign) {
        return res.json(new ERR('sign不为空!', 400));
    }
    if (!checkOvertime(par.time)) {
        return res.json(new ERR('时间戳已过期!', 400));
    }

    //1.加密生成签名sign
    var param = createSign({
        url: par.url,
        app_sid: par.app_sid,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if (param.sign == param.sign) {
        //2.签名验证成功，进入dao层发起http请求获取access_token
        ocrDao.handwriting(param, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (data.status == 200) {
                    return res.json(new PKG(data));
                } else {
                    return res.json(new ERR(data, 420));
                }
            }
        });
    } else {
        return res.json(new ERR('sign算法不合法!', 420));
    }
});

router.post('/idcard', function (req, res) {
    var par = paramAll(req);

    if (!par.time) {
        par.time = new Date().getTime();
    }
    if (!par.sign) {
        return res.json(new ERR('sign不为空!', 400));
    }
    if (!checkOvertime(par.time)) {
        return res.json(new ERR('时间戳已过期!', 400));
    }

    //1.加密生成签名sign
    var param = createSign({
        url: par.url,
        app_sid: par.app_sid,
        time: new Date().getTime()
    }, CONFIG.SIGNSECRET);

    if (param.sign == param.sign) {
        //2.签名验证成功，进入dao层发起http请求获取access_token
        ocrDao.idcard(param, function (err, data) {
            if (err) {
                return res.json(new ERR(err, 410));
            } else {
                if (data.status == 200) {
                    return res.json(new PKG(data));
                } else {
                    return res.json(new ERR(data, 420));
                }
            }
        });
    } else {
        return res.json(new ERR('sign算法不合法!', 420));
    }
});

module.exports = router;